/*
# A component of the Realistic Book software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2007 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/*****************************************************************
Realistic Book application
	Detect Flash Player 8.0.24 or more plugin 
	Specify the XHTML input and image cover URL to program
	Embed the program to the div tag with id = bookdiv

by Veronica Liesaputra --- 1 August 2007
******************************************************************/

var doc_url;// XHTML url
var img_cover;// image cover url
var anno_url;// XHTML annotation url

//check internet browser type
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var doc_width = -1;
var doc_height = -1;
var doc_style = "";
var init_page = "";
var http_request = false;

//These functions will be called by the program
function getDocURL() { return doc_url; }
function getImgCover() { return img_cover; }
function getStageW() { return doc_width; }
function getStageH() { return doc_height; }
function setDocumentTitle(doc_title) { document.title = doc_title; }
function getStyleFile() { return doc_style; }
function getStartOpenPage() { return init_page; }
function getAnnoURL() { return anno_url; }
function getScreenW() { return screen.width; }
function getScreenH() { return screen.height; }

//set the page where the book will be open to
function setOpenPage(num) { init_page = num; }
//set the style of the book
function setBookStyle(s) {doc_style = s;}
//set the size of the book
function setBookSize(dw,dh) {doc_width = dw; doc_height = dh;}

//overload function
function embedBookProgram(args)
{
	if (init_page.length == 0) {
		var loc = window.location.href;
		var idx = loc.lastIndexOf("#");
		if (idx != -1) {
			var aftr = loc.substring(idx + 1);
			if ((aftr.indexOf(".") == -1) && (aftr.indexOf("?") == -1))
				init_page = aftr;
		}
	}
	if (args.length == 0)
		alert("Please type the URL for the XHTML input");
	else
	{
		var size = [-1, -1];
		var file_url = ["","",""];
		var slen = 0;
		var surl = 0;
		for (var i = 0; i < args.length; i++) {
			if (isNaN(args[i]) == true) {
				file_url[surl] = args[i];
				surl++;
			}  else {
				size[slen] = args[i];
				slen++;
			}
		}
		
		embedProgram(file_url[0],file_url[1],size[0],size[1],file_url[2]);
	} 
}

/*
 * If user has Flash player 8.0.24 or more, Embed the program to your HTML file
 * inside the div tag with id = bookdiv Set the doc_url, img_cover, anno_url, stage_width
 * and stage_height value Otherwise, Show user the links to get the flash player
 */
function embedProgram(xhtml_url, image_url, stage_height, stage_width,note_url)
{
	var flash_plug_html = "";
	var flash_width = "100%";
	if (stage_width != -1)
		flash_width = "" + stage_width;
	var flash_height = "100%";
	if (stage_height != -1)
		flash_height = "" + stage_height;

	if (detectFlashPlayerVersion(8,0,24) == false)
	{
		flash_plug_html += 'This content requires the Adobe Flash Player 8.0.24 or greater.';
		flash_plug_html += '<a href=http://www.macromedia.com/go/getflash/>Get Flash</a>';
	}
	else
	{
		doc_url = escape(''+xhtml_url);// just in case user forgot the quote
		img_cover = escape(''+image_url);
		if (note_url == "") {
			var ind = xhtml_url.lastIndexOf(".");
			if (ind != -1) {
				note_url = xhtml_url.substring(0, ind) + "_annotation" + xhtml_url.substring(ind, xhtml_url.length);
			}	
		}
		anno_url = escape(''+note_url);

		// embed inside object tag for IE
		flash_plug_html += '<OBJECT align="middle" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" \n';
		flash_plug_html += '  codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" \n';
		flash_plug_html += '  height="' + flash_height + '" id="Book" swLiveConnect="true" align="middle"\n';
		flash_plug_html += ' allowFullScreen="true"\n';
		flash_plug_html += '  width="' + flash_width + '">\n';
		// embed inside embed tag for netscape, mozilla
		flash_plug_html += '<PARAM name="allowScriptAccess" value="always" />\n';
		flash_plug_html += '<PARAM name="movie" value="RealisticBook.swf';
		flash_plug_html += '?src_image=' + img_cover;
		flash_plug_html += '&amp;stageW=' + doc_width;
		flash_plug_html += '&amp;stageH=' + doc_height;
		flash_plug_html += '&amp;doc_url=' + doc_url;
		flash_plug_html += '&amp;anno_url=' + anno_url;
		flash_plug_html += '" />\n';
		flash_plug_html += '<PARAM name="quality" value="high" />\n';
		flash_plug_html += '<PARAM name="allowFullScreen" value="true" />\n';
		flash_plug_html += '<PARAM name="bgcolor" value="#FFFFFF" />\n';
		flash_plug_html += '<EMBED align="middle" \n';
		flash_plug_html += '      allowScriptAccess="always" swLiveConnect="true" \n';
		flash_plug_html += '      bgcolor="#FFFFFF" height="' + flash_height + '" name="Book" \n';
		flash_plug_html += '      pluginspage="http://www.macromedia.com/go/getflashplayer" \n';
		flash_plug_html += '      quality="high" allowFullScreen="true" \n';
		flash_plug_html += '      src=\'RealisticBook.swf';
		flash_plug_html += '?src_image=' + img_cover;
		flash_plug_html += '&amp;stageW=' + doc_width;
		flash_plug_html += '&amp;stageH=' + doc_height;
		flash_plug_html += '&amp;doc_url=' + doc_url;
		flash_plug_html += '&amp;anno_url=' + anno_url;
		flash_plug_html += '\'\n'; 
		flash_plug_html += '      type="application/x-shockwave-flash" width="' + flash_width + '" />\n';
		flash_plug_html += '</OBJECT>\n';
	}

	var flash_div = document.getElementById('bookdiv');
	flash_div.innerHTML = flash_plug_html;
}

function detectFlashPlayerVersion(reqMajor,reqMinor,reqRevision)
{
	if (navigator.plugins != null && navigator.plugins.length > 0) 
	{
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) 
		{
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") 
			{
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") 
			{
				versionRevision = versionRevision.substring(1);
			}
			else if (versionRevision[0] == "r") 
			{
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) 
				{
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}

			var isGood = isGoodPlugin(reqMajor,reqMinor,reqRevision,versionMajor,versionMinor,versionRevision);
			return isGood;
		}
	}
	else if ( isIE && isWin && !isOpera ) 
	{
		var version;
		var axo;
		var e;

		try 
		{
			// version will be set for 7.X or greater players
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			version = axo.GetVariable("$version");

			// Given "WIN 2,0,0,11"
			var tempArray = version.split(" "); 	// ["WIN", "2,0,0,11"]
			var tempString = tempArray[1];		// "2,0,0,11"
			var versionArray = tempString.split(",");	// ['2', '0', '0', '11']

			var isGood = isGoodPlugin(reqMajor,reqMinor,reqRevision,versionArray[0],versionArray[1],versionArray[2]);
			return isGood;
		} 
		catch (e) {}
	}

	return false;
}

/*
 * Check whether the current flash player plugin passed the required version
 */
function isGoodPlugin(reqMajor,reqMinor,reqRevision,currMajor,currMinor,currRevision)
{
	if (currMajor > parseFloat(reqMajor)) 
	{
		return true;
	} 
	else if (currMajor == parseFloat(reqMajor)) 
	{
		if (currMinor > parseFloat(reqMinor))
		{
			return true;
		}
		else if (currMinor == parseFloat(reqMinor)) 
		{
			if (currRevision >= parseFloat(reqRevision))
			{		
				return true;
			}
		}
	}

	return false;
}

function makePOSTRequest(url, parameters) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			// http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = sendStatus;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}

function sendStatus() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var res = http_request.responseText;
			res = res.replace("&result=no error","");
			res = res.replace("&msg=","");
			alert(res);
		}
		/*else {
			alert('There was a problem with the request.');
		}*/
	}
}

function saveText(msg) {
	var postStr = 'msgFile=' + escape(encodeURIComponent(doc_url)); 
	postStr += '&msgText=' + escape(encodeURIComponent(msg));
	makePOSTRequest('send.php',postStr);
}

function saveNote(msg) {
	var postStr = 'msgFile=' + escape(encodeURIComponent(anno_url)); 
	postStr += '&msgText=' + escape(encodeURIComponent(msg));
	makePOSTRequest('send.php',postStr);
}

window.onbeforeunload = saveBook;
function saveBook() {
	var flashBook = document["Book"];
	if (navigator.appName.indexOf("Microsoft") != -1) {
        	flashBook = window["Book"];
    	}
   	
	if (flashBook != null) {
		flashBook.saveBookNotes();
		//flashBook.saveBookTexts();
	}
}